<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <title>角色授权</title>
  {% include 'rbac/common/add-edit-header.html' %}
</head>
<style>
  .container {
    display: flex;
  }

  .button-container {
    position: fixed;
    right: 20px;
    top: 20px;
    display: flex;
    flex-direction: column;
  }

  .button-container button {
    margin-top: 10px;
  }
</style>
<body>

<form id="role-rights-form" lay-filter="role-rights-form">
  <div class="container">
    <!-- 左侧表单区域 -->
    <div id="role-power-tree"></div>

    <!-- 右侧固定按钮区域 -->
    <div class="button-container">
      <div class="layui-input-block">
        <button type="submit" class="layui-btn layui-btn-sm" lay-submit lay-filter="role-power-form-btn">确认</button>
        <button type="reset" class="layui-btn layui-btn-sm" lay-on="rolePowerReload">重置</button>
      </div>
    </div>
  </div>
</form>

{% include 'rbac/common/add-edit-footer.html' %}
<script>
  let token = "{{ csrf_token }}";
  solve_csrf(token)

  layui.use(["tree", "table", "form", "popup", 'util'], function () {
    let tree = layui.tree;
    let $ = layui.$;
    let table = layui.table;
    let popup = layui.popup;
    let util = layui.util;
    let form = layui.form;

    // 获取所有权限数据展现树形结构，并自动在树中选中当前角色所拥有的权限
    function get_role_power_tree_data() {
      $.ajax({
        url: `/api/v1/role/power_get/?id={{role_obj.id}}`,
        type: "get",
        success: function (ret) {
          tree.render({
            elem: '#role-power-tree',
            id: 'role-power-tree',
            data: ret.data,  // 展示有哪些权限
            showCheckbox: true,
            // edit: ['add', 'update', 'del'] // 开启节点的右侧操作图标
          });
          // console.log("展示时默认选中的权限id", ret.select)
          tree.setChecked("role-power-tree", ret.select);  // 选中权限
        },
      });
    }

    // 打开权限授权页面时,先获取一次当前角色的权限数据
    get_role_power_tree_data();
    // 重置按钮事件 (本质就是再发起一次获取权限数据的ajax请求)
    util.event('lay-on', {
      rolePowerReload: function () {
        get_role_power_tree_data();
      }
    });

    // 更新当前角色的所拥有的权限!!
    form.on("submit(role-power-form-btn)", function (data) {
      let checkData = tree.getChecked("role-power-tree"); // 获取选中节点的数据
      let rights_ids = get_layui_tree_id(checkData).join();

      let url = "/api/v1/role/power_update/"
      let d = {power_ids: rights_ids, role_id: {{role_obj.id}}} // 授哪些权,给哪个角色授权
      let reload_table = ""  // 授权成功后没必要刷新表格
      addAndEditAjaxRequest(popup, url, d, reload_table)
      return false;
    });
  });
</script>

</body>
</html>